package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.handler.GroupBuyOrderCommitHandler;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.YgGroup;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgTuan;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.SessionUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 促销相关
 *
 * @author guohao
 */
@Controller
@RequestMapping("/mobile/grouporder")
public class YgGroupOrderController extends BaseController {
    @Autowired
    private YgOrderLogService ygOrderLogService;
    @Autowired
    private YgOrderService orderService;
    @Autowired
    private YgShoppingCarService shoppingCarService;
    @Autowired
    private YgGroupBuyingService ygGroupBuyingService;
    @Autowired
    private DocumentConstant documentConstant;
    @Autowired
    private YgGroupService ygGroupService;
    @Autowired
    private YgSalesPromotionService ygSalesPromotionService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private YgTuanService ygTuanService;
    @Autowired
    private TrustoneService trustoneService;
    @Autowired
    private GroupBuyOrderCommitHandler groupBuyOrderCommitHandler;

    private final SalesPlatform salesPlatform = SalesPlatform.Yiigoo;

    private String DISABLE_COUPON_KEY = "disablecoupon";

    /**
     * 商品详情页获取该分组下进行中的开团信息
     *
     * @param groupId
     * @param callback
     * @return
     */
    @RequestMapping(value = "findGroupBuyByGroupId")
    @ResponseBody
    public JSONPObject findGroupByPid(QueryInfo queryInfo, Long groupId, String callback) {
        List<YgGroupBuyModel> models = ygGroupBuyingService.findGroupBuyByGroupId(queryInfo, groupId);
        Map<String, Object> map = new HashMap<String, Object>();
        YgGroup group = ygGroupService.findById(groupId);
        map.put("groupAmount", group.getGroupAmount());
        map.put("groupMode", group.getGroupMode());
        map.put("groupBuyList", models);

        return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));

    }

    /**
     * 获取某团信息
     *
     * @param groupBuyId
     * @param callback
     * @return
     */
    @RequestMapping(value = "findGroupBuyById")
    @ResponseBody
    public JSONPObject findGroupBuyById(Long groupBuyId, String callback) {
        YgGroupBuyModel model = ygGroupBuyingService.findGroupBuyById(groupBuyId);
        return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));

    }

    /**
     * 获取拼团商品信息
     *
     * @param productId
     * @param callback
     * @return
     */
    @RequestMapping(value = "findProductInfoWithGroup")
    @ResponseBody
    public JSONPObject findProductInfoWithGroup(Long productId, String callback) {
        YgProductGroupModel model = ygGroupBuyingService.findProductInfoWithGroup(productId);
        return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));

    }

    /**
     * 获取其他拼团商品信息
     *
     * @param groupBuyId
     * @param callback
     * @return
     */
    @RequestMapping(value = "findOtherGroupProduct")
    @ResponseBody
    public JSONPObject findOtherGroupProduct(QueryInfo queryInfo, Long productId, String callback) {
        List<YgProductGroupModel> model = ygGroupBuyingService.findOtherGroupProduct(queryInfo, productId);
        return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));

    }

    /**
     * 获取所有未完成的拼团
     *
     * @param callback
     * @return
     */
    @RequestMapping(value = "findAllGroupBuy")
    @ResponseBody
    public JSONPObject findAllGroupBuy(QueryInfo queryInfo, String callback) {
        List<YgGroupBuyModel> model = ygGroupBuyingService.findAllGroupBuy(queryInfo);
        return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));

    }

    /**
     * 拼团结算页获取商品信息
     *
     * @param skuIds
     * @param callback
     * @return
     * @throws YgException
     */
    @RequestMapping(value = "findItemInfoPt")
    @ResponseBody
    public JSONPObject findItemInfoPt(String skuInfos, @RequestParam(defaultValue = "false") Boolean distribution, String callback) throws YgException {
        JSONPObject json;

        Map<String, Object> map = new HashMap<String, Object>();

        YgUser user = SessionUtil.getCurrentUser();
        List<YgPtSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<YgPtSkuInfo>>() {
        });
        List<YgShoppingCarModel> list = shoppingCarService.findItemInfoPt(skuList, user.getId(), distribution);
        StringBuilder sb = new StringBuilder();
        BigDecimal productPrice = new BigDecimal("0.00");
        BigDecimal specialPrice = new BigDecimal("0.00");
        BigDecimal vipPrice = new BigDecimal("0.00");
        BigDecimal totalPromotionPrice = new BigDecimal("0.00");
        for (YgShoppingCarModel model : list) {
            if (model.getPromotionPrice().compareTo(new BigDecimal("0")) == 0) {
                sb.append(model.getProductName()).append(",skuid=").append(model.getSkuId()).append(";");
            }
            productPrice = productPrice.add(model.getSalesPrice().multiply(new BigDecimal(model.getQuantity())));
            totalPromotionPrice = totalPromotionPrice.add(model.getRealSalesPrice().multiply(new BigDecimal(model.getQuantity())));

            if (PromotionType.IsSpecial.equals(model.getSalesType())) {
                specialPrice = specialPrice.add(model.getRealSalesPrice().multiply(new BigDecimal(model.getQuantity())));
            }
            BigDecimal vPrice = model.getVipPrice();
            if (vPrice == null || vPrice.compareTo(new BigDecimal("0.00")) == 0) {
                vPrice = model.getRealSalesPrice();
            }
            vipPrice = vipPrice.add(vPrice.multiply(new BigDecimal(model.getQuantity())));
        }
        if (sb.length() > 0) {
            sb.append("上述商品不是拼团商品");
            throw new YgException("-1", sb.toString());
        }
        List<List<YgShoppingCarModel>> sortCarList = shoppingCarService.sortCarList(list, user.getId());
        map.put("carList", sortCarList);
        map.put("productPrice", productPrice);
        map.put("specialPrice", totalPromotionPrice);
        map.put("vipDisPrice", totalPromotionPrice.subtract(vipPrice));
        map.put("trustoneFlag", trustoneService.validateIsTrustonerOrder(list));
        json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
        return json;
    }

    @RequestMapping(value = "commitOrderPt")
    @ResponseBody
    public JSONPObject commitOrderPt(@RequestParam(defaultValue = "false") Boolean distribution, String skuInfos, Long groupId, Long groupBuyId,
                                     Long userAddressId, Long couponDetailId, AppType appType, PayType payType, BigDecimal totalPrice,
                                     String formId, String callback, String sourceCode, BigDecimal accountPrice, String userRemark, String platformNo,
                                     String identityNo, HttpServletRequest request) throws YgException {

        if (PayType.Small.equals(payType)) {
            payType = PayType.WeChat;
        }

        JSONPObject json;
        YgUser user = SessionUtil.getCurrentUser();
        String openid = user.getOpenId();
        if (StringUtils.isBlank(sourceCode) || sourceCode.equals("undefined")) {
            sourceCode = null;
        }
        couponDetailId = validateDisableCouponFromRedis(couponDetailId);
        Message msg;
        List<YgPtSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<YgPtSkuInfo>>() {
        });
        Boolean isNew = ygUserService.isNewCustom(user.getId());
        msg = ygGroupBuyingService.checkNewCustomGroup(skuList, isNew, accountPrice);
        if (msg.getType().equals(Message.Type.error)) {
            return new JSONPObject(callback, msg);
        }

        ygOrderLogService.addOrderLog(user.getId(), OrderStatus.WaitingPay, user.getUserName(), "提交订单,【入参】：skuInfos=" + skuInfos + ";groupId=" + groupId + ";" +
                "" + "" + "" + "" + "" + "" + "" + "" + "groupBuyId=" + groupBuyId + ";userAddressId=" + userAddressId + ";couponDetailId=" + couponDetailId
                + ";" + "appType=" + appType + ";" + "payType=" + payType + ";totalPrice=" + totalPrice + ";formId=" + formId + ";sourceCode" + sourceCode +
                ";" + "accountPrice=" + accountPrice + ";" + "userRemark=" + userRemark + ";platformNo=" + platformNo + ";identityNo=" + identityNo);

        // 校验核销
        msg = ygSalesPromotionService.checkHeXiao(skuList, user.getId());
        if (msg.getType().equals(Message.Type.error)) {
            return new JSONPObject(callback, msg);
        }
        OrderType orderType = OrderType.GroupBuying;
        if ((Boolean) msg.getExtra()) {
            orderType = OrderType.HeXiao;
        }

        // 卡券订单
        if (request.getAttribute("sourceOrderType") != null && request.getAttribute("sourceOrderType").toString().endsWith(OrderType.CardCoupon.name())) {
            orderType = OrderType.CardCoupon;
        } else {

            YgGroup group = ygGroupService.findById(groupId);
            // 老带新 只限新用户参团，老用户只能发起拼团
            if (GroupMode.OldBeltNew.equals(group.getGroupMode())) {
                if (groupBuyId != null && groupBuyId != 0 && !isNew) {
                    return new JSONPObject(callback, Message.error("亲，该拼团只限新用户参团。", groupBuyId + "-" + isNew));
                }
                Long quantity = skuList.get(0).getQuantity();
                if (skuList.size() > 1 || quantity > 1) {
                    return new JSONPObject(callback, Message.error("亲，该拼团限一件。", groupBuyId + "-" + isNew));
                }

            } else if (GroupMode.OnlyNew.equals(group.getGroupMode()) && !isNew) {
                return new JSONPObject(callback, Message.error("亲，该拼团只限新用户。", groupBuyId + "-" + isNew));
            }

        }

        // 保存订单
//        msg = orderService.commitOrderPt(skuList, user.getId(), user.getUserName(), userAddressId, couponDetailId, totalPrice, appType, payType, sourceCode,
//                accountPrice, formId, groupId, groupBuyId, orderType, userRemark, platformNo, identityNo, salesPlatform,distribution);

        GroupOrderCommitParam commitParam = new GroupOrderCommitParam(skuList, user.getId(), user.getUserName(), userAddressId, couponDetailId, totalPrice, appType, payType, sourceCode,
                accountPrice, formId, groupId, groupBuyId, orderType, userRemark, platformNo, identityNo, salesPlatform, distribution);
        msg = groupBuyOrderCommitHandler.commitOrder(commitParam);

        // 订单保存成功
        if (msg.getType().equals(Message.Type.success)) {
            Map<String, Object> map = (Map<String, Object>) msg.getExtra();
            map.put("openid", openid);
            map.put("totalPrice", totalPrice.subtract(accountPrice));
            msg.setExtra(map);
            msg.setContent("订单提交成功");
            ygOrderLogService.addOrderLog((Long) map.get("orderId"), OrderStatus.WaitingPay, user.getUserName(), "订单提交成功：" + map.toString());
        } else {
            logger.error("订单提交失败，msgType:" + msg.getType() + ";msg:" + msg.getContent() + ";msgExtra:" + (msg.getExtra() == null ? "" : msg.getExtra()
                    .toString()));
        }

        json = new JSONPObject(callback, msg);
        return json;
    }

    /**
     * 验证优惠券禁用设置
     *
     * @return
     */
    @SuppressWarnings("rawtypes")
    private Long validateDisableCouponFromRedis(Long couponDetailId) {
        try {
            String couponInfo = redisDao.get(DISABLE_COUPON_KEY);
            Map map = JSON.parseObject(couponInfo, Map.class);
            if (MapUtils.isEmpty(map)) {
                return couponDetailId;
            }
            Long currentTime = new Date().getTime();
            String startDate = map.get("startDate").toString();
            String endDate = map.get("endDate").toString();
            String format = "yyyy-MM-dd HH:mm:ss";
            Long startTime = DateConvertUtils.parse(startDate + " 00:00:00", format).getTime();
            Long endTime = DateConvertUtils.parse(endDate + " 23:59:59", format).getTime();
            if (startTime.compareTo(currentTime) > 0 || endTime.compareTo(currentTime) < 0) {
                return couponDetailId;
            }
        } catch (Exception e) {
            logger.error("验证优惠券禁用设置异常，" + ExceptionUtil.getExceptionMsg(e));
            return couponDetailId;
        }
        return null;
    }

    /**
     * @param queryInfo
     * @param orderStatus
     * @param callback
     * @return JSONPObject 返回类型
     * @throws @date 2017年7月5日 下午12:07:41
     * @Title: findOrderListByHeXiao
     * @Description: 获取核销列表页
     * @author （guohao）
     * @version V1.0
     */
    @RequestMapping(value = "findOrderListByHeXiao", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findOrderListByHeXiao(QueryInfo queryInfo, String userName, String callback) {
        List<YgOrderModel> orderList = orderService.findOrderListByHeXiao(queryInfo, OrderStatus.WaitingSend, userName);
        JSONPObject json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, orderList));
        return json;
    }

    /**
     * 确认收货
     *
     * @param orderId
     * @param callback
     * @return
     */
    @RequestMapping(value = "confirmHeXiao", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject confirmReceipt(Long orderId, String callback) {
        YgOrder ygOrder = new YgOrder();
        ygOrder.setOrderId(orderId);
        ygOrder.setWdtOrderCode("HX" + orderId);
        ygOrder.setOrderStatus(OrderStatus.TradeSuccess);
        ygOrder.setConfirmReceiveTime(new Date());
        int i = orderService.updateByOrderId(ygOrder);
        return new JSONPObject(callback, Message.success(i));
    }

    /**
     * 拼团Banner列
     *
     * @param callback
     * @return
     */
    @RequestMapping(value = "findTuanData", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findTuanData(String callback, QueryInfo queryInfo, @RequestParam(defaultValue = "Ordinary") GroupMode groupMode, String attribute) {
        Map<String, Object> data = new HashMap<>();
        List<YgTuan> currentTuanList = ygTuanService.findList(queryInfo, PromotionStatus.Running, null, null, groupMode, attribute);
        List<YgTuan> futureTuanList = ygTuanService.findList(queryInfo, PromotionStatus.NotStarted, null, null, groupMode, attribute);
        data.put("currentTuanList", currentTuanList);
        data.put("futureTuanList", futureTuanList);
        data.put("currentTimeZone", new Date().getTime());
        return new JSONPObject(callback, Message.success(data));
    }

    @RequestMapping(value = "findTuanMemberList", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findTuanMemberList(String callback, Long groupBuyId) {
        List<Map<String, Object>> list = ygGroupBuyingService.findTuanMemberList(groupBuyId);
        return new JSONPObject(callback, Message.success(list));
    }

    @RequestMapping(value = "findTuanAttribute", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findTuanAttribute(String callback) {
        return new JSONPObject(callback, Message.success(ygTuanService.findTuanAttribute()));
    }

}
